<?php
global $AppUI;

// check permissions
$m = $AppUI->checkFileName(dPgetParam( $_GET, 'm', getReadableModule() ));
$denyEdit = getDenyEdit( $m );
if ($denyEdit) {
	$AppUI->setMsg('Access denied', UI_MSG_ERROR);
	$AppUI->redirect();
}

$perms = &$AppUI->acl();
$needCheckCostCenter = $perms->userHasRole($AppUI->user_id, "FFIA_Staff") || $perms->userHasRole($AppUI->user_id, "Operation");

require_once $AppUI->getSystemClass('date');
require_once( $AppUI->getModuleClass( 'projects' ) );

$df = $AppUI->getPref('SHDATEFORMAT');

$tid = isset($_GET['tid']) ? $_GET['tid'] : 0;
$q = new DBQuery();
$task = array();
if ($tid > 0) {
	$q->addTable('task_log', 'tl');
	$q->addQuery('tl.*,t.task_project');
	$q->addJoin('tasks', 't', 'tl.task_log_task = t.task_id');
	$q->addWhere('task_log_id = '.$tid);
	$task = $q->loadHash();
	$task_project = $task['task_project'];
	$creator = isset($task['task_log_creator']) ? $task['task_log_creator'] : 0;

	//load task log item info
	require_once( $AppUI->getModuleClass( 'items' ) );
	$itemO = new CItem();
	$itemO->load($task['task_log_item']);
	$task['task_log_item_code'] = $itemO->item_code;
	$task['task_log_item_name'] = $itemO->item_name;
	$task['task_log_item_type'] = $itemO->item_type1_name;

	// Load list transportation
	$q = new DBQuery();
	$q->addTable('task_log_transportations');
	$q->addWhere('tlog_task_log = '.$tid);
	$q->addJoin('transportations', 'tran', 'task_log_transportations.tlog_transportation = tran.trans_id');
	$q->addQuery('tlog_task_log, tlog_transportation, tlog_driver, tran.trans_name');
	$q->addOrder('tlog_driver');
	$sql = $q->prepare();
	$q->clear();
	$trans_list = db_loadList($sql);
}
else {
	$creator = $AppUI->user_id;

	// TODO:
	//	Get task from task_id if exits
	$task_id = intval(dPgetParam($_GET, "task_id", 0));
	$task_project = intval(dPgetParam($_GET, "task_project", 0));
	if(0 < $task_id){
		require_once($AppUI->getModuleClass('tasks'));
		$objTask = new CTask();
		$objTask->load($task_id);

		if(isset($objTask->task_project)){
			$task_project = $objTask->task_project;
			$task['task_log_task'] = $objTask->task_id;
		}
	}
}

if (isset( $task['task_log_date'] )) {
	$date = new CDate( $task['task_log_date'] );
} else if (isset( $_GET['date'] )) {
	$date = new CDate($_GET['date']);
} else {
	$date = new CDate();
}

// trangdt replace
/*
$q->addTable('projects', 'p');
$q->addTable('project_contacts', 'pc');
$q->addQuery('p.project_id,p.project_name,p.project_owner');
$q->addWhere('p.project_id = pc.project_id');
$q->addWhere('p.project_status > 0 AND  p.project_status < 6');
$q->addWhere('pc.contact_id = '.$AppUI->user_id);
*/
require_once $AppUI->getModuleClass('admin');
require_once $AppUI->getModuleClass('contacts');
$user = new CUser();
$user->load($AppUI->user_id);
$contact = new CContact();
$contact->load($user->user_contact);
$projectCompletedSysVal = dPgetSysVal( 'ProjectCompleted' );
$q->addTable('projects', 'p');
if ($task_project > 0) {
	$q->addWhere("project_id = $task_project");
}
//$q->addWhere('p.project_rstatus = '.$projectCompletedSysVal);
// trangdt end
$projects = $q->loadHashList('project_id');
$project = array('' => '-');
$taskList = '';
foreach ($projects as $id => $p) {
	$q->addTable('tasks', 't');
	$q->addQuery('t.task_id,t.task_name,t.task_percent_complete,t.task_project');
//	if ($p['project_owner'] != $AppUI->user_id) {
//		$q->addJoin('user_tasks', 'ut', 't.task_id = ut.task_id');
//		$q->addWhere('ut.user_id = '.$AppUI->user_id);
//	}
	$q->addWhere('t.task_project = '.$id);
	$q->addWhere('t.task_percent_complete < 100'.(($id == $task_project and isset($task['task_log_task']))? ' OR t.task_id = '.$task['task_log_task'] : ''));
	// trandt add
	//$q->addWhere('t.task_division='. $contact->contact_division);
	if ($needCheckCostCenter) {
		$q->addWhere('t.task_costcenter='. $AppUI->user_costcenter);
	}
	// trangdt end
	$tasks = $q->loadHashList('task_id');
	if (count($tasks) > 0) {
		$project[$id] = $p['project_name'];
		$taskList .= '['.$id.',';
		foreach ($tasks as $zid => $t) {
			$taskList .= '['.$zid.',"'.addslashes(html_entity_decode($t['task_name'])).'",'.$t['task_percent_complete'].'],';
		}
		$taskList .= '0],'."\n";
	}
}
// TODO:
// Each project/company may have its own billing code
// => load Billing code for each project
$q = new DBQuery();
$q->addTable('billingcode');
$q->addQuery('billingcode_id,billingcode_name');
$q->addWhere('billingcode_status = 0');

$task_log_costcodes = $q->loadHashList();
$task_log_costcodes = arrayMerge(array(0 => 'None'), $task_log_costcodes);

require_once($AppUI->getMasterDataClass( 'mddivision' ));
$divisionList = arrayMerge(array( '' => '' ), getDivisionList());

require_once($AppUI->getMasterDataClass( 'mdcostcenter' ));
$costcenterList = arrayMerge(array( '' => '' ), getCostCenterList());

require_once($AppUI->getModuleClass( 'suppliers' ));
$supplierList = getSupplierList();

$q = new DBQuery();
$q->addTable('users', 'u');
$q->addTable('contacts', 'c');
//$q->addTable('project_contacts', 'pc');
$q->addQuery('user_id, concat(contact_first_name, \' \', contact_last_name) as contact_name');
//$q->addWhere('pc.contact_id = u.user_id AND u.user_contact = c.contact_id AND pc.project_id = '.$task_project);
$q->addWhere('u.user_contact = c.contact_id');
$q->addOrder('contact_first_name');
$sql = $q->prepare();
$resourceList = db_loadHashList($sql);

$expenseList = dPgetSysVal('TaskLogExpense');

// Load item list
require_once($AppUI->getModuleClass('items'));
$iO = new CItem();
$itemList = $iO->getItemsList4AutoCompleter('TaskLogItem');

// Curency list
require_once($AppUI->getMasterDataClass('mdcurrency'));
$objMD = new CMdCurrency();
$curList = $objMD->getCurrencyList();
$curList = arrayMerge(array(''=>''), $curList);

?>

<script language="javascript">
var taskList = [<?=$taskList?>];
var tlogId = <?=$tid?>;

function changeProject(sel) {
	var pid = sel.options[sel.selectedIndex].value;
	var t = $('idTaskList');

	t.options.length = 0;
	$('idTask_complete').value = 0;
	for (i in taskList) {
		if (taskList[i] == 0) return;
		var p = taskList[i];
		if (p[0] == pid) {
			var n = 0;
			t.options[n++] = new Option('-', '');
			for (z = 1; p[z] != 0; z++) {
				var opt = new Option(p[z][1], p[z][0]);
				t.options[n++] = opt;
				opt.setAttribute('percent', p[z][2]);
			}
			break;
		}
		$('idTask_complete').value = 100;
	}
}

function changeTask(sel, tid) {
	if (typeof(tid) != 'undefined') {
		for (var i = 0; i < sel.options.length; i++)
			if (sel.options[i].value == tid) {
				sel.selectedIndex = i;
				break;
			}
	}
	var tc = $('idTask_complete');
	if (sel.selectedIndex <= 0)
		tc.value = 0;
	else {
		var p = sel.options[sel.selectedIndex].getAttribute('percent');
		if (tlogId == 0) {
			tc.value = 100;
		} else if (p && p != '') {
			tc.value = p;
		}
		$('idTaskName').value = sel.options[sel.selectedIndex].text;
	}
}
/*
function doSave() {
	var f = document.AddEdit;

	if (f.task_log_description.value.length < 1) {
		alert( "Please enter a worthwhile comment." );
		f.task_log_description.focus();
	} else if (f.task_project.selectedIndex == 0) {
		alert( "You must select a Project." );
		f.task_project.focus();
	} else if (f.task_log_task.selectedIndex == 0) {
		alert( "You must select a Task." );
		f.task_log_task.focus();
	} else {
		f.submit();
	}
}
*/
function doCancel()
{
	if (confirm('Are you sure you want to cancel.')) {
		//location.href = './index.php?m=timecard&tab=0';
		history.go(-1);
	}
}

function doDelete() {
	if (confirm( "Are you sure that you would like to delete this task log?\n" )) {
		var form = document.AddEdit;
		form.del.value=1;
		form.submit();
	}
}

function createNewTask() {
	var p = $('idProjectList');
	if (p.selectedIndex <= 0) {
		alert('Please select a project');
		return;
	}
	go('?m=tasks&a=simpleaddedit&task_project='+p.options[p.selectedIndex].value);
}

function doSelectItem(itemObj) {
	if(itemObj==null){
		$('task_log_item_id').value = '';
		$('task_log_item_autocompleter').value = '';
		$('idTaskLogItemName').value = '';
		$('idTaskItemType').value = '';
	}
	else{
		$('task_log_item_id').value = itemObj.id;
		$('task_log_item_autocompleter').value = itemObj.code;
		$('idTaskLogItemName').value = itemObj.name;
		$('idTaskItemType').value = itemObj.type;
	}
	setTimeout('$("idTaskLogAmount").focus()', 100);
}
</script>

<form name="AddEdit" action="" method="post">
<input type="hidden" name="m" value="timecard">
<input type="hidden" name="tab" value="0">
<input type="hidden" name="dosql" value="do_updatetasklog">
<input type="hidden" name="del" value="0">
<input type="hidden" name="task_log_id" value="<?=$tid?>">
<input type="hidden" name="task_log_creator" value="<?=$creator?>"/>

<table cellspacing="0" cellpadding="4" border="0" width="100%" class="infopanel">
<tr>
	<td>
		<input class="button" type="submit" name="btnFuseAction" value="save">
	</td>
	<td>
		<input class="button" type="submit" name="save_new" value="save & new">
	</td>
	<td>
		<input class="button" type="button" name="Cancel" value="cancel" onClick="doCancel()">
	</td>
	<td width="100%" align="right">
	<?	if ($tid > 0) { ?>
		<a class="button" href="javascript:doDelete()"><img align="absmiddle" src="images/delete_log.gif" title="Delete">&nbsp;<?=$AppUI->_('delete task log')?></a>
	<?	} ?>&nbsp;
	</td>
</tr>
</table>
<table cellspacing="0" cellpadding="4" border="0" width="100%" class="subinfopanel">
<tr>
<td valign="top" style="width: 400px">
<table cellspacing="0" cellpadding="4" border="0" width="100%">
<tr>
	<td align="right" nowrap="nowrap"><b>* <?=$AppUI->_('Item code');?></b></td>
	<td colspan="3">
		<?= arrayAutoSelectLocalItem($itemList, 'task_log_item', ' style="width: 250px" maxlength="50"', @$task['task_log_item'], false, @$task['task_log_item_code'], 'doSelectItem');?>
	</td>
</tr>
<tr>
	<td align="right" nowrap="nowrap"><?=$AppUI->_('Item name');?></td>
	<td colspan="3">
		<input id="idTaskLogItemName"  type="text" class="text" name="item_name"
			value="<?=$task['task_log_item_name']?>" style="width:98%" maxlength="255" readonly="true"/>
	</td>
</tr>
<tr>
	<td align="right"><?=$AppUI->_('Item type');?></td>
	<td colspan="3">
		<input id="idTaskItemType"  type="text" class="text" name="item_type"
			value="<?=$task['task_log_item_type']?>" style="width:98%" maxlength="255" readonly="true"/>
	</td>
</tr>
<tr>
	<td nowrap="nowrap" align="right"> * <?=$AppUI->_('Currency')?></td>
	<td>
		<?= arraySelect($curList, 'task_log_currency', ' id="task_log_currency" size="1" class="text" style="width: 80px;" onchange="doChangeCurrency(this);" title="Hint :: Currency is required"', @$task['task_log_currency'], true)?>
	</td>
	<td align="right" nowrap="nowrap" nowrap="nowrap">* <?=$AppUI->_('Expense');?></td>
	<td width="110px">
		<?= arraySelect( $expenseList, 'task_log_expense',
			'class="text" style="text-transform: capitalize; width:100px;"', $task['task_log_expense'], true )?>
	</td>
</tr>
<tr>
	<td align="right" nowrap><b>* <?=$AppUI->_('Expense Amount');?></b></td>
	<td>
		<input id="idTaskLogAmount" title="Amount :: Amount is required" type="text" class="text" style ="width: 80px; text-align: right" name="task_log_amount_origin"
			value="<?=isset($task['task_log_amount_origin']) ? currencyFormat($task['task_log_amount_origin'], $task['task_log_currency']):""?>" onkeyup="return (currencyFormat(this, ',', currencyCode(), event))"/>
	</td>
	<td nowrap="nowrap" align="right">
		 * <?=$AppUI->_('Exchange')?>
	</td>
	<td>
		<input type="text" class="text" name="task_log_exchange_rate" id="task_log_exchange_rate" <?=@$task['task_log_currency'] == CURRENCY_VND_VALUE ? "readonly='true'" : ""?> style="width: 100px; text-align: right;" value="<?=@$task['task_log_exchange_rate']?>" autocomplete="off" title="Hint :: Exchange rate is required and should be numericality"/>
	</td>
</tr>
<tr>
	<td align="right">* <?=$AppUI->_('Division');?></td>
	<td colspan="3">
		<?=arraySelect( $divisionList, 'task_log_division',
			'id="idTaskLogDivision" title="Division :: Division is required" class="text" style="text-transform: capitalize; width: 100%"',
			$task['task_log_division'], true )?>
	</td>
</tr>
<tr>
	<td align="right" nowrap="nowrap">* <?=$AppUI->_('Cost center');?></td>
	<td colspan="3">
		<?=arraySelect( $costcenterList, 'task_log_costcenter',
			'id="idTaskLogCostCenter" title="CostCenter :: CostCenter is required" class="text" style="text-transform: capitalize; width: 100%"',
			$task['task_log_costcenter'], true )?>
	</td>
</tr>
<tr>
	<td align="right">* <?=$AppUI->_('Resource');?></td>
	<td colspan="3">
		<?=arraySelect( $resourceList, 'task_log_resource',
			'id="idTaskLogResource" title="Resource :: Resource is required" class="text" style="text-transform: capitalize; width: 100%"',
			$task['task_log_resource'], true )?>
	</td>
</tr>
<tr>
	<td align="right"><?=$AppUI->_('Supplier');?></td>
	<td colspan="3">
		<?=arraySelect( $supplierList, 'task_log_transporter',
			'class="text" style="text-transform: capitalize; width: 100%"',
			$task['task_log_transporter'], true )?>
	</td>
</tr>
<tr>
	<td align="right" ><?=$AppUI->_('Trucks and Drivers');?></td>
	<td nowrap="nowrap"><image src="images/add.gif" border="0" class="clickable" onClick="doShowSearchTruckDialog()"></td>
	<td colspan="2">&nbsp;</td>
</tr>
<tr>
	<td>&nbsp;</td>
	<td colspan="3">
		<div class='text' style="width: 98%; height: 100px; overflow: auto">
			<table id="idTableTrucks" border="0" cellspacing="1" cellpadding="4" width="92%">
			<?php if(isset($trans_list)):?>
			<?php foreach($trans_list as $trans):?>
				<tr id="transId_<?=$trans['tlog_task_log']?>">
					<td><?=$trans['trans_name']?></td>
					<td>
						<input type="hidden" name="task_log_transportation_ids[]" value="<?=$trans['tlog_transportation']?>"/>
						<input type="text" name="task_log_transportations[]" value="<?=$trans['tlog_driver']?>"/>
					</td>
					<td><img border="0" src="images/delete.png" onclick="removeTransport('transId_<?=$trans['tlog_task_log']?>', '<?=$trans['trans_name']?>');"/></td>
				</tr>
			<?php endforeach;endif;?>
			</table>
		</div>
	</td>
</tr>
</table>
</td>
<td>
	<img src="images/blank.gif" height="1" width="10px"/>
</td>
<td valign="top">
<table cellspacing="0" cellpadding="4" border="0" width="100%">
<tr>
	<td align="right" nowrap="nowrap"><b>* <?=$AppUI->_('Reference')?>:</b></td>
	<td colspan="5">
		<?
			$params = 'id="idProjectList" title="Project :: Project is required" size="1" class="text" style="width:350px" ';
			$params .= 'onchange="changeProject(this)"';
			echo arraySelect( $project, 'task_project', $params, $task_project);
		?>
	</td>
</tr>
<tr>
	<td align="right" nowrap="nowrap">* <?=$AppUI->_('Task')?></td>
	<td colspan="5">
		<select id="idTaskList" title="Task: Task is required" name="task_log_task" class="text" style="width:320px" onchange="changeTask(this)"></select>
		<input id="idTaskName" type="hidden" name="task_log_name" value="">
		<input type="image" src="images/add_task.gif" onclick="createNewTask(); return false" class="button" title="Create new task"/>
	</td>
</tr>
<tr>
	<td align="right" nowrap="nowrap"><?=$AppUI->_('Start date')?></td>
	<td nowrap="nowrap">
		<input id="idDateStartLog" type="hidden" name="task_log_date" value="<?=$date->format(FMT_TIMESTAMP_DATE)?>">
		<input id="idDateStartLogD" style="width: 70px" type="text" name="date" value="<?=$date->format($df)?>" class="text" disabled="disabled">
		<img id="idDateStartLogB" align="absmiddle" src="images/calendar.gif" title="<?=$AppUI->_('Calendar')?>">
	</td>
	<td align="right" nowrap="nowrap"><b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<?=$AppUI->_('Completion')?></b></td>
	<td width="50%" align="left">
		<?=showSpinBox('task_complete', 100, 0, 100, '%', 20, false, 85)?>
	</td>
</tr>
<tr>
	<td align="right" nowrap="nowrap"><?=$AppUI->_('End Date')?></td>
	<td nowrap="nowrap">
		<input id="idDateEndLog" type="hidden" name="task_log_date" value="<?=$date->format(FMT_TIMESTAMP_DATE)?>">
		<input id="idDateEndLogD" style="width: 70px" type="text" name="date" value="<?=$date->format($df)?>" class="text" disabled="disabled">
		<img id="idDateEndLogB" align="absmiddle" src="images/calendar.gif" title="<?=$AppUI->_('Calendar')?>">
	</td>
	<td align="right" nowrap="nowrap"><?=$AppUI->_('Hours')?></td>
	<td>
		<?=showSpinBox('task_log_hours', ($tid > 0) ? $task['task_log_hours'] : '0', 0, 9, '', 0.5, false, 85)?>
	</td>
</tr>
<tr>
	<td align="right"><?=$AppUI->_('Container')?></td>
	<td nowrap="nowrap">
		<input id="idTaskLogContainers" title="Number of Container"  type="text" class="text" name="task_log_number_of_container"
			value="<?=$task['task_log_number_of_container']?>" style="width: 100px; text-align: right" maxlength="20" />
	</td>
	<td align="right"><?=$AppUI->_('Fuel')?></td>
	<td colspan="2" nowrap="nowrap">
		<input id="idTaskLogFuel" title="Fuel"  type="text" class="text" name="task_log_fuel"
			value="<?=$task['task_log_fuel']?>" style="width: 100px; text-align: right" maxlength="20" />
	</td>
</tr>
<tr>
	<td align="right"><?=$AppUI->_('Distance')?></td>
	<td nowrap="nowrap">
		<input id="idTaskLogDistance" title="Distance"  type="text" class="text" name="task_log_distance"
			value="<?=$task['task_log_distance']?>" style="width: 100px; text-align: right" maxlength="20" />
	</td>
	<td align="right"><?=$AppUI->_('Package')?></td>
	<td colspan="2" nowrap="nowrap">
		<input id="task_log_package"  type="text" class="text" name="task_log_package"
			value="<?=$task['task_log_package']?>" style="width: 100px; text-align: right" maxlength="255" />
	</td>
</tr>
<tr>
	<td align="right" valign="top" nowrap="nowrap"><?=$AppUI->_('Location')?></td>
	<td align="left" colspan="5">
		<textarea name="task_log_location" style="width: 350px" rows="2" wrap="virtual" class="textarea"><?php echo (($tid > 0) ? $task["task_log_location"] : "");?></textarea>
	</td>
</tr>
<tr>
	<td align="right" valign="top" nowrap="nowrap"><?=$AppUI->_('From')?></td>
	<td align="left" colspan="5">
		<textarea name="task_log_from" style="width: 350px" rows="2" wrap="virtual" class="textarea"><?php echo (($tid > 0) ? $task["task_log_from"] : "");?></textarea>
	</td>
</tr>
<tr>
	<td align="right" valign="top" nowrap="nowrap"><?=$AppUI->_('To')?></td>
	<td align="left" colspan="5">
		<textarea name="task_log_to" style="width: 350px" rows="2" wrap="virtual" class="textarea"><?php echo (($tid > 0) ? $task["task_log_to"] : "");?></textarea>
	</td>
</tr>
<tr>
	<td align="right" valign="top" nowrap="nowrap"><?=$AppUI->_('Description')?></td>
	<td align="left" colspan="5" style=" height: 100%">
		<textarea name="task_log_description" style="width: 350px;" rows="2" wrap="virtual" class="textarea"><?php echo (($tid > 0) ? $task["task_log_description"] : "");?></textarea>
	</td>
</tr>
<tr style="display: none">
	<td align="right" nowrap="nowrap"><?=$AppUI->_('Cost Code')?>:</td>
	<td align="left" colspan="5">
		<?php
			echo arraySelect( $task_log_costcodes, 'task_log_costcodes', 'size="1" class="text" onchange="javascript:task_log_costcode.value = this.options[this.selectedIndex].value;"', '' );
		?>
		&nbsp;->&nbsp;<input type="text" class="text" name="task_log_costcode" value="<?php echo $task["task_log_costcode"]?>" maxlength="8" size="8" />
	</td>
</tr>
<tr style="display: none">
	<td>&nbsp;</td>
	<td align="left" colspan="6" width="100%" valign="top" style="padding: 0px">
		<table border="0" cellspacing="0" cellpadding="0">
			<tr>
				<td><input id="idTaskProblem" type="checkbox" value="1" name="task_log_problem" <? echo $task["task_log_problem"] ? 'checked="checked"' : ''; ?> /></td>
				<td><label for="idTaskProblem"><?php echo $AppUI->_('Problem');?></label></td>
			</tr>
		</table>
	</td>
</tr>
</table>
</td>
</tr>
</table>
</form>

<div id="idTransportationsLiveSearchBox" class="popup" style="visibility: hidden; height: 400px; left: 436px; top: 94.5px; display: none;">
	<?php require_once(DP_BASE_DIR."/modules/masterdata/transportations/livesearch.php");?>
</div>
<script language="javascript">

function doShowSearchTruckDialog() {
	new Dialog('idTransportationsLiveSearchBox',
		function(){
			Dialog('idTransportationsLiveSearchBox').hide();
		}).show();
}

function doSelectTruck(transId, transCode, transName, contName) {
	Dialog('idTransportationsLiveSearchBox').hide();//dong truoc chac an

    //output the results
	if ($('transId_' + transId) != null) {
		alert('<?=$AppUI->_('Truck existed')?>');
		return;
	}
    var tableCon = $('idTableTrucks');
    var trCon = new Element('tr').injectInside(tableCon);
    trCon.id = 'transId_' + transId;
    var tdCon = new Element('td').setHTML(transCode).injectInside(trCon);
    var tdCon1 = new Element('td').injectInside(trCon);
    var inp = new Element('input', {'type' : 'hidden', 'name' : 'task_log_transportation_ids[]', 'value' : transId, 'maxlength' : '64'}).injectInside(tdCon1);
    var inp1 = new Element('input').injectInside(tdCon1);
    inp1.type = 'text';
    inp1.name = 'task_log_transportations[]';
    inp1.value = contName;

    var tdCon2 = new Element('td').injectInside(trCon);
    var img = new Element('img', {'src' : 'images/delete.png', 'border' : '0', 'onclick' : 'removeTransport("transId_' + transId + '","' + transName+ '")'}).injectInside(tdCon2);
}

function removeTransport(id, str){
	if(confirm('Are you seure to remove ' + str)){
		$(id).remove();
	}
	return false;
}

function closeDialog(id){
    Control(id).destroy();
	Dialog(id).hide();
}

</script>
<script language="javascript">
Calendar.enabled = true;
function init() {
	changeProject($('idProjectList'));
	<? if ($tid > 0 || (isset($task['task_log_task']) && $task['task_log_task'] > 0)) { ?>
		changeTask($('idTaskList'), <?=$task['task_log_task']?>);
	<? } ?>
}

setTimeout('init()', 250);
</script>
<div id="validation_rules" style="visibility: hidden; display: none">
	var fTaskLogItemCode = new LiveValidation('task_log_item_autocompleter');
	fTaskLogItemCode.add( Validate.Presence);

	var fTaskLogAmount = new LiveValidation('idTaskLogAmount');
	fTaskLogAmount.add( Validate.Presence );
	fTaskLogAmount.add( Validate.Numericality, {minimum: 1, maximum: 99999999999} );

	var fTaskLogContainers = new LiveValidation('idTaskLogContainers');
	fTaskLogContainers.add( Validate.Numericality, {minimum: 0, maximum: 99999999999} );

	var fTaskLogFuel = new LiveValidation('idTaskLogFuel');
	fTaskLogFuel.add( Validate.Numericality, {minimum: 0, maximum: 99999999999} );

	var fTaskLogDistance = new LiveValidation('idTaskLogDistance');
	fTaskLogDistance.add( Validate.Numericality, {minimum: 0, maximum: 99999999999} );

	var fTaskLogCostCenter = new LiveValidation('idTaskLogCostCenter');
	fTaskLogCostCenter.add( Validate.Presence );

	var fTaskLogDivision = new LiveValidation('idTaskLogDivision');
	fTaskLogDivision.add( Validate.Presence );

	var fTaskLogResource = new LiveValidation('idTaskLogResource');
	fTaskLogResource.add( Validate.Presence );

	var fProjectList = new LiveValidation('idProjectList');
	fProjectList.add( Validate.Presence );
	var fTaskList = new LiveValidation('idTaskList');
	fTaskList.add( Validate.Presence );

//	new Tips($$('.text'));
</div>
<script type="text/javascript" language="javascript">
	eval($('validation_rules').innerHTML);

	function doChangeCurrency(sel) {
		var vnd_value = "<?=CURRENCY_VND_VALUE?>";
		if(sel.value == ""){
			$('task_log_exchange_rate').readOnly = "true";
			$('idTaskLogAmount').readOnly = "true";
		}
		else{			
			$('idTaskLogAmount').removeAttribute("readOnly");
			var amount_val = $('idTaskLogAmount').value;
			var ind = amount_val.indexOf(".");
			
			if (sel.value == vnd_value) {
				$('task_log_exchange_rate').value = 1;
				$('task_log_exchange_rate').readOnly = "true";
				
				// remove separate decimal
				if(ind > 0){
					$('idTaskLogAmount').value = amount_val.substr(0,ind);
				}
			}
			else{
				$('task_log_exchange_rate').value = "";
				$('task_log_exchange_rate').removeAttribute("readOnly");
				
				// addition decimal
				if(ind == -1){
					$('idTaskLogAmount').value = amount_val.concat(".00");
				}
			}
		}
	}

	function currencyCode() {
		var vnd_value = "<?=CURRENCY_VND_VALUE?>";
		var sel = $("task_log_currency").value;
		if (sel == vnd_value) {
			return "";
		}
		return ".";
	}
	
	// Call doChangeCurrency when onload page to check 'select Currency'
	doChangeCurrency($("task_log_currency"));
</script>
